<template>
  <div class="register">
    <van-nav-bar title="用户注册" left-arrow @click-left="$router.push('/login')" />
    <div class="container">
      <div class="title">
        <h3>手机号注册</h3>
      </div>
      <van-form @submit="onSubmit" class="form">
        <div class="field-wrapper">
          <van-field
            class="form-item"
            v-model="formData.phone"
            type="tel"
            name="phone"
            label="手机号码"
            placeholder="请输入手机号码"
            @input="validatePhone"
          />
          <span class="error-message" v-if="errors.phone">{{ errors.phone }}</span>
        </div>

        <div class="field-wrapper">
          <van-field
            class="form-item"
            v-model="formData.nickname"
            type="text"
            name="nickname"
            label="用户昵称"
            placeholder="请输入昵称"
            @input="validateNickname"
          />
          <span class="error-message" v-if="errors.nickname">{{ errors.nickname }}</span>
        </div>

        <div class="field-wrapper">
          <van-field
            class="form-item"
            v-model="formData.password"
            type="password"
            name="password"
            label="登录密码"
            placeholder="请输入密码"
            @input="validatePassword"
          />
          <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
        </div>

        <div class="field-wrapper">
          <van-field
            class="form-item"
            v-model="formData.confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            @input="validateConfirmPassword"
          />
          <span class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
        </div>

        <div class="field-wrapper">
          <van-field
            class="form-item"
            v-model="formData.code"
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
            @input="validateCode"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                :disabled="!isPhoneValid"
                @click="sendCode"
              >
                {{ countDownText }}
              </van-button>
            </template>
          </van-field>
          <span class="error-message" v-if="errors.code">{{ errors.code }}</span>
        </div>

        <div style="margin: 16px;" class="register-btn">
          <van-button round block type="info" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
      <div>验证码 {{ noteCode }}</div>
    </div>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getMsgCode } from '@/api/login'
import { register } from '@/api/user'

export default {
  name: 'UserRegister',
  data () {
    return {
      formData: {
        phone: '',
        nickname: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      errors: {
        phone: '',
        nickname: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      isPhoneValid: false,
      countdown: 60,
      isCountingDown: false,
      noteCode: '请先请求获取验证码'// 请求获取返回的验证码
    }
  },
  computed: {
    countDownText () {
      return this.isCountingDown ? `${this.countdown}秒后重试` : '获取验证码'
    }
  },
  methods: {
    // 验证手机号
    validatePhone () {
      if (!this.formData.phone) {
        this.errors.phone = '请输入手机号'
        this.isPhoneValid = false
      } else if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        this.errors.phone = '请输入正确的手机号'
        this.isPhoneValid = false
      } else {
        this.errors.phone = ''
        this.isPhoneValid = true
      }
    },

    // 验证昵称
    validateNickname () {
      if (!this.formData.nickname) {
        this.errors.nickname = '请输入昵称'
      } else if (this.formData.nickname.length < 2 || this.formData.nickname.length > 20) {
        this.errors.nickname = '昵称长度应在2-20个字符之间'
      } else {
        this.errors.nickname = ''
      }
    },

    // 验证密码
    validatePassword () {
      if (!this.formData.password) {
        this.errors.password = '请输入密码'
      } else if (!/^\d{4,12}$/.test(this.formData.password)) {
        this.errors.password = '密码必须是4-12位数字'
      } else {
        this.errors.password = ''
      }
      // 当密码改变时，同时验证确认密码
      if (this.formData.confirmPassword) {
        this.validateConfirmPassword()
      }
    },

    // 验证确认密码
    validateConfirmPassword () {
      if (!this.formData.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
      } else if (this.formData.password !== this.formData.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
      } else {
        this.errors.confirmPassword = ''
      }
    },

    // 验证验证码
    validateCode () {
      if (!this.formData.code) {
        this.errors.code = '请输入验证码'
      } else if (!/^\d{6}$/.test(this.formData.code)) {
        this.errors.code = '验证码必须是6位数字'
      } else {
        this.errors.code = ''
      }
    },

    startCountDown () {
      this.isCountingDown = true
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.isCountingDown = false
          this.countdown = 60
        }
      }, 1000)
    },
    async sendCode () {
      if (!this.isPhoneValid) {
        Toast('请输入正确的手机号码')
        return
      }
      try {
        // 这里调用发送验证码的API
        const { data } = await getMsgCode(this.formData.phone)
        if (data) {
          this.noteCode = data
          console.log('短信验证码为：', data)
        }
        Toast('验证码发送成功')
        this.startCountDown()
      } catch (error) {
        Toast('验证码发送失败')
      }
    },
    async onSubmit (values) {
      // 触发所有验证
      this.validatePhone()
      this.validateNickname()
      this.validatePassword()
      this.validateConfirmPassword()
      this.validateCode()

      // 检查是否有错误
      if (Object.values(this.errors).some(error => error)) {
        return
      }

      try {
        await register(this.formData)
        Toast.success('注册成功')
        await this.$router.replace('/login')
      } catch (error) {
        Toast.fail('注册失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.register {
  padding-bottom: 50px;
}
.container {
  padding: 49px 29px;

  .title {
    margin-bottom: 20px;
    h3 {
      font-size: 26px;
      font-weight: normal;
    }
    p {
      line-height: 40px;
      font-size: 14px;
      color: #b8b8b8;
    }
  }

  .field-wrapper {
    position: relative;
    margin-bottom: 20px;

    .form-item {
      margin-bottom: 0;
      border-bottom: 1px solid #f3f1f2;
      padding: 8px;
      display: flex;
      align-items: center;
      img {
        width: 94px;
        height: 31px;
      }
      button {
        height: 31px;
        border: none;
        font-size: 13px;
        color: #cea26a;
        background-color: transparent;
        padding-right: 9px;
      }
    }

    .error-message {
      position: absolute;
      left: 16px;
      bottom: -20px;
      font-size: 12px;
      color: #ff4d4f;
      line-height: 1.5;
    }
  }

  .login-btn {
    width: 100%;
    height: 42px;
    margin-top: 39px;
    background: linear-gradient(90deg,#ecb53c,#ff9211);
    color: #fff;
    border-radius: 39px;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.1);
    letter-spacing: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
